//
// Created by edward on 23-5-17.
//

#include "utils.h"
#include "worker.h"

//struct callback worker_cb;
int fd;

void reply(const char * msg) {
    Write(fd, msg, strlen(msg));
}

void run_worker(const char* ip, int port) {
    fd = Socket(AF_INET, SOCK_STREAM, 0);
    easy_connect(fd, port, ip);
    reply("I am a new worker");

    char buf[BUFSIZ];
    while (true) {
        int ret = Read(fd, buf, BUFSIZ - 1);
        if (ret > 0) {
            buf[ret] = '\0';
//            log.print("[client " + clientSocket.ip + ":" + to_string(clientSocket.port) + "]\n{" + buf +"}");
            printf("controller sent: %s\n", buf);
//            Write(fd, buf, ret);
        } else if (ret < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
            //读数据结束
//            log.print("[client " + clientSocket.ip + ":" + to_string(clientSocket.port) + "]\n{read end}");
//            printf("controller sent end\n");
            break;
        } else {
            printf("controller disconnect\n");
            break;
        }
    }
}
